﻿using System;
using System.Collections;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Xml.Serialization;
using CodeBadger.GasMileage.Models;

namespace CodeBadger.GasMileage.Persistence
{
    public class IsolatedStorageGateway
    {
        private const string StorageFile = "data.txt";
        private readonly XmlSerializer _serializer;

        public IsolatedStorageGateway()
        {
            _serializer = new XmlSerializer(typeof (Notebook));
        }

        public Notebook LoadNotebook()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = GetStorageStreamForReading(store))
                using (var reader = new StreamReader(stream))
                {
                    return reader.EndOfStream 
                        ? new Notebook() 
                        : (Notebook) _serializer.Deserialize(reader);
                }
            }
        }

        public void Save(Notebook notebook)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = GetStorageStreamForWriting(store))
            {
                _serializer.Serialize(stream, notebook);
            }
        }

        private static IsolatedStorageFileStream GetStorageStreamForWriting(IsolatedStorageFile store)
        {
            return new IsolatedStorageFileStream(StorageFile, FileMode.Create, FileAccess.Write, store);
        }

        private static IsolatedStorageFileStream GetStorageStreamForReading(IsolatedStorageFile store)
        {
            return new IsolatedStorageFileStream(StorageFile, FileMode.OpenOrCreate, FileAccess.Read, store);
        }
    }
}
